package com.stars.easyms.redis.interceptor;

import com.stars.easyms.base.util.ReflectUtil;
import com.stars.easyms.base.util.TimeUtil;
import com.stars.easyms.redis.annotion.RedisSetAdd;
import com.stars.easyms.redis.exception.RedisInterceptorException;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>className: RedisSetAddInterceptor</p>
 * <p>description: RedisSetAdd注解拦截器</p>
 *
 * @author
 * @date 2019-12-24 17:44
 */
public class RedisSetAddInterceptor extends AbstractRedisInterceptor<RedisSetAdd> {


    @Override
    Object invoke(MethodInvocation methodInvocation, RedisSetAdd redisSetAdd) throws RedisInterceptorException {
        Object result = proceed(methodInvocation);
        if(isEnabled()  && result != null){
            Method pointMethod = methodInvocation.getMethod();
            Class<?> returnType = pointMethod.getReturnType();
            boolean isInvalidReturnType = !(List.class.isAssignableFrom(returnType) || Set.class.isAssignableFrom(returnType) || Object.class.isAssignableFrom(returnType));
            if (isInvalidReturnType) {
                logger.error("Method '{}'  returnType should be List or Object!", ReflectUtil.getMethodFullName(pointMethod));
            }
            String redisKey = getRedisKey(methodInvocation, redisSetAdd.group());
            if(List.class.isAssignableFrom(returnType)){
                easyMsRedisTemplate.setAdd(redisKey, (List<Object>) result);
            }else if(Set.class.isAssignableFrom(returnType)){
                easyMsRedisTemplate.setAdd(redisKey, (Set<Object>) result);
            }else{
                easyMsRedisTemplate.setAdd(redisKey, result);
            }
            Long expire = getExpire(methodInvocation);
            expire = expire != null ? expire : TimeUtil.parseToMilliseconds(redisSetAdd.expire());
            boolean isSetExpire = expire != null && expire > 0 && (redisSetAdd.resetExpire() || easyMsRedisTemplate.getExpire(redisKey, TimeUnit.MILLISECONDS) <= 0);
            if (isSetExpire) {
                easyMsRedisTemplate.expire(redisKey, expire, TimeUnit.MILLISECONDS);
            }
        }
        return result;
    }
}